package com.carleasoft.mps.adu.business.role.service.impl;


import com.carleasoft.mps.adu.business.role.bean.vo.AuthorityDataPermsVo;
import com.carleasoft.mps.adu.business.role.dao.AuthorityDataPermsDao;
import com.carleasoft.mps.adu.business.role.dao.AuthorityDataDao;
import com.carleasoft.mps.adu.business.role.service.AuthorityPermDataService;
import com.carleasoft.mps.core.user.Constants;
import com.carleasoft.mps.core.tree.DataBizTreeVo;
import com.carleasoft.mps.core.tree.TreeBuild;
import com.carleasoft.mps.core.user.ThreadUserContext;
import com.carleasoft.mps.core.user.UserCacheData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>Description: role serviceImpl</p>
 *
 * @author ztm
 * @since 2020-05-11
 */
@Service
public class AuthorityPermDataServiceImpl implements AuthorityPermDataService {
    @Autowired
    AuthorityDataDao authorityDataDao;
    @Autowired
    AuthorityDataPermsDao authorityDataPermsDao;

    /**
     * 登录用户数据权限查询封装，要解决所属部门和所属组织权限
     *
     * @param roleCodes
     * @return AuthorityRoleVo
     */
    public AuthorityDataPermsVo getDataPermCodesNeedConvert(List<String> roleCodes, Boolean isLogin,Boolean isInc) {
        AuthorityDataPermsVo authorityDataPermsVo = new AuthorityDataPermsVo();
        List<AuthorityDataPermsVo> authorityDataPermsVos = new ArrayList<>();
        if (roleCodes == null || roleCodes.size() == 0) {
            UserCacheData userCacheData = ThreadUserContext.getCurrentCacheUser();

            if (userCacheData.getUserCat() != Constants.SUPER_ADMIN) {
                return authorityDataPermsVo;
            } else {
                AuthorityDataPermsVo authorityDataPermsVoTemp = new AuthorityDataPermsVo();
                authorityDataPermsVoTemp.setDataType(Constants.DATA_ALL);
                authorityDataPermsVos.add(authorityDataPermsVoTemp);

            }
        } else {
            authorityDataPermsVos = authorityDataPermsDao.selectDataPermissionsByRoleCodes(roleCodes);
            if (authorityDataPermsVos == null || authorityDataPermsVos.size() == 0) return authorityDataPermsVo;
            if (authorityDataPermsVos != null && authorityDataPermsVos.size() == 1) {
//                authorityDataPermsVo=authorityDataPermsVos.get(0);
                BeanUtils.copyProperties(authorityDataPermsVos.get(0),authorityDataPermsVo);
            }
        }

        for (AuthorityDataPermsVo item : authorityDataPermsVos) {
            if (item.getDataType() < authorityDataPermsVo.getDataType())
                authorityDataPermsVo.setDataType(item.getDataType());
            if (authorityDataPermsVo.getDataType() == Constants.DATA_ALL) {
                List<String> ttt = authorityDataDao.selectOrgTypeCodesByOrgType(null);
                authorityDataPermsVo.setOrgTypeCodes(ttt);

                List<String> ooo = authorityDataDao.selectOrgCodesByOrgType(ttt,isInc);
                authorityDataPermsVo.setOrgCodes(ooo);

                List<String> ddd = authorityDataDao.selectDeptCodesByOrgCodes(ooo,isInc);
                authorityDataPermsVo.setDeptCodes(ddd);

            }

            //获取组织分类+组织+部门编码
            if (item.getDataType() == Constants.DATA_ORGANIZATION_TYPE) {

                item.getPermCodes().forEach((typeCode) -> {
                    List<String> ttt = authorityDataDao.selectOrgTypeCodesByOrgType(typeCode);
                    if (ttt != null & ttt.size() > 0) {
                        List<String> tempOrgTypeCodes = Stream.of(authorityDataPermsVo.getOrgTypeCodes(), ttt)
                                .flatMap(Collection::stream).distinct().collect(Collectors.toList());
                        authorityDataPermsVo.setOrgTypeCodes(tempOrgTypeCodes);

                        List<String> ooo = authorityDataDao.selectOrgCodesByOrgType(ttt,isInc);
                        List<String> tempOrgCodes = Stream.of(authorityDataPermsVo.getOrgCodes(), ooo)
                                .flatMap(Collection::stream).distinct().collect(Collectors.toList());
                        authorityDataPermsVo.setOrgCodes(tempOrgCodes);


                        List<String> ddd = authorityDataDao.selectDeptCodesByOrgCodes(ooo,isInc);
                        List<String> tempDeptCodes = Stream.of(authorityDataPermsVo.getDeptCodes(), ddd)
                                .flatMap(Collection::stream).distinct().collect(Collectors.toList());
                        authorityDataPermsVo.setDeptCodes(tempDeptCodes);

                    }
                });

            }
            //构建组织+部门
            if (item.getDataType() == Constants.DATA_SELECT_ORGANIZATION) {
                //组织树,组织不需要树结构
                List<String> ooo = authorityDataDao.selectOrgCodesByOrgCodes(item.getPermCodes(),isInc);
                List<String> tempOrgCodes = Stream.of(authorityDataPermsVo.getOrgCodes(), ooo)
                        .flatMap(Collection::stream).distinct().collect(Collectors.toList());
                authorityDataPermsVo.setOrgCodes(tempOrgCodes);


                List<String> ddd = authorityDataDao.selectDeptCodesByOrgCodes(ooo,isInc);
                List<String> tempDeptCodes = Stream.of(authorityDataPermsVo.getDeptCodes(), ddd)
                        .flatMap(Collection::stream).distinct().collect(Collectors.toList());
                authorityDataPermsVo.setDeptCodes(tempDeptCodes);

            }
            if (item.getDataType() == Constants.DATA_OWNER_ORGANIZATION) {
                //组织树,组织不需要树结构
                UserCacheData userCacheData = ThreadUserContext.getCurrentCacheUser();
                if (isLogin&&userCacheData.getUserCat()!=Constants.SYSTEM_ADMIN) {
                    List<String> ooo = Arrays.asList(userCacheData.getOrgCodeJoin().split(","));
                    //todo 这段代码有问题
                    List<String> tempOrgCodes = Stream.of(authorityDataPermsVo.getOrgCodes(), ooo)
                            .flatMap(Collection::stream).distinct().collect(Collectors.toList());
                    authorityDataPermsVo.setOrgCodes(tempOrgCodes);


                    List<String> ddd = authorityDataDao.selectDeptCodesByOrgCodes(ooo,isInc);
                    List<String> tempDeptCodes = Stream.of(authorityDataPermsVo.getDeptCodes(), ddd)
                            .flatMap(Collection::stream).distinct().collect(Collectors.toList());
                    authorityDataPermsVo.setDeptCodes(tempDeptCodes);
                }

            }
            //构建部门code
            if (item.getDataType() == Constants.DATA_SELECT_DEPT) {
                //部门树
                item.getPermCodes().forEach((deptCode) -> {
                    List<String> ddd = authorityDataDao.selectDeptCodesByDeptCode(deptCode,isInc);
                    List<String> tempDeptCodes = Stream.of(authorityDataPermsVo.getDeptCodes(), ddd)
                            .flatMap(Collection::stream).distinct().collect(Collectors.toList());
                    authorityDataPermsVo.setDeptCodes(tempDeptCodes);

                });
            }
            if (item.getDataType() == Constants.DATA_OWNER_DEPT) {
                UserCacheData userCacheData = ThreadUserContext.getCurrentCacheUser();
                if (isLogin&&userCacheData.getUserCat()!=Constants.SYSTEM_ADMIN) {

                    List<String> ddd = Arrays.asList(userCacheData.getDeptCodeJoin().split(","));
                    List<String> tempDeptCodes = Stream.of(authorityDataPermsVo.getDeptCodes(), ddd)
                            .flatMap(Collection::stream).distinct().collect(Collectors.toList());
                    authorityDataPermsVo.setDeptCodes(tempDeptCodes);

                }
            }
        }
        return authorityDataPermsVo;
    }

    /**
     * 数据权限换算为树
     *
     * @param
     * @return AuthorityRoleVo
     */
    public void analyseDataPermAsTree(AuthorityDataPermsVo authorityDataPermsVo) {
        List<String> typeCodes = authorityDataPermsVo.getOrgTypeCodes();
        List<String> orgCodes = authorityDataPermsVo.getOrgCodes();
        List<String> deptCodes = authorityDataPermsVo.getDeptCodes();

        if (typeCodes != null && typeCodes.size()>0) {
            List<DataBizTreeVo> orgTypeTree = this.authorityDataDao.selectTreeByCodes(typeCodes, null, null);
            authorityDataPermsVo.setOrgTypeDataBizTreeVoList(this.buildTree(orgTypeTree, typeCodes));
        }
        if (orgCodes != null && orgCodes.size()>0) {
            List<DataBizTreeVo> orgTree = this.authorityDataDao.selectTreeByCodes(typeCodes, orgCodes, null);
            List<String> ttoo = new ArrayList<>();
            if (typeCodes != null && typeCodes.size()>0) {
                ttoo.addAll(typeCodes);
            }
            ttoo.addAll(orgCodes);
            authorityDataPermsVo.setOrgDataBizTreeVoList(this.buildTree(orgTree, ttoo));
        }

        if (deptCodes != null && deptCodes.size()>0) {
            List<DataBizTreeVo> deptTree = this.authorityDataDao.selectTreeByCodes(typeCodes, null, deptCodes);
            List<String> ddoo = new ArrayList<>();
            if (typeCodes != null && typeCodes.size()>0) {
                ddoo.addAll(typeCodes);
            }
            ddoo.addAll(deptCodes);
            authorityDataPermsVo.setDeptDataBizTreeVoList(this.buildTree(deptTree, ddoo));

        }

    }

    //解析树
    private List<DataBizTreeVo> buildTree(List<DataBizTreeVo> list, List<String> targetCodes) {
        //找出顶级节点编码
        List<String> plist = new ArrayList<>();
        for (DataBizTreeVo dataBizTreeVo : list) {
            if (!targetCodes.contains(dataBizTreeVo.getParentTargetCode())) {
                //不加载父节点，从当前节点开始追，所以以当前节点code为父亲编码
                plist.add(dataBizTreeVo.getTargetCode());
            }
        }
        List<DataBizTreeVo> last = new ArrayList<>();
        for (String pCode : plist) {
            last.addAll(TreeBuild.getTreeListFromCurrent(pCode, list));
        }

        return last;

    }
}
